package com.pms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.entity.CameraUserInformation;
import com.pms.entity.IotEqCamera;
import com.pms.exception.R;
import com.pms.mapper.IotEqCameraMapper;
import com.pms.mapper.RelationTableMapper;
import com.pms.service.ICameraUserInformationService;
import com.pms.service.IRelationTableService;
import com.pms.util.FluoriteCloudUtile;
import com.pms.validator.Assert;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RelationTableServiceImpl  implements IRelationTableService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    RelationTableMapper relationTableMapper;
    @Autowired
    IotEqCameraMapper eqCameraMapper;
    @Autowired
    private ICameraUserInformationService service;

    @Override
    @Transactional
    public Integer cleanUpCompanyData(String companyCode) {
        try {
            // 删除摄像头
            Wrapper<IotEqCamera> wrapper =new EntityWrapper<IotEqCamera>();
            wrapper.eq("company_code",companyCode);
            List<IotEqCamera> cameraList=eqCameraMapper.selectList(wrapper );
            for (int x=0,len=cameraList.size();x<len;x++){
                JSONObject cloud = FluoriteCloudUtile.deletefluoriteCloud(cameraList.get(x).getKey(),cameraList.get(x).getToken());
                if(cloud.getString("code").equals("200")){
                    CameraUserInformation user=service.selectById(cameraList.get(x).getCameraUserId());
                    Assert.isNull(user,"该摄像头用户配置信息不存在");
                    user.setSum(user.getSum()-1);
                    eqCameraMapper.deleteById(cameraList.get(x).getEqId());
                    service.updateAllColumnById(user);
                }else{
                    logger.error("删除序列号{"+cameraList.get(x).getKey()+"}摄像头失败,错误码为"+cloud.get("code"));
                    logger.error( cloud.get("msg").toString() );
                }
            }
            // 需先删除摄像头
            relationTableMapper.cleanUpCompanyAgencyData(companyCode);
            relationTableMapper.cleanUpCompanyWaterGroupData(companyCode);
            return  1;
        }catch (Exception ex){
            logger.error("删除公司二供数据出错,公司编码为:"+companyCode);
            ex.printStackTrace();
            throw  ex;
        }
    }
}
